<template>
  <Center>
    <form class="login-container" @submit.prevent="handleSubmit">
      <div class="form-item">
        <div class="input">
          <label>账号: </label
          ><input
            v-model="userInfo.loginId"
            type="text"
            @input="validateEmpty('loginId', '账号不能为空')"
          />
        </div>
        <FormError :msg="error.loginId" />
      </div>
      <div class="form-item">
        <div class="input">
          <label>密码: </label
          ><input
            v-model="userInfo.loginPwd"
            type="password"
            autocomplete="new-password"
            @input="validateEmpty('loginPwd', '密码不能为空')"
          />
        </div>
        <FormError :msg="error.loginPwd" />
      </div>
      <div class="form-item">
        <div class="input">
          <label></label>
          <button>
            {{ $store.state.loginUser.isLoading ? '正在登录中...' : '登录' }}
          </button>
        </div>
      </div>
    </form>
  </Center>
</template>

<script>
import Center from '@/components/Center'
import FormError from '@/components/FormError'
// import { login } from '../services/userService'

export default {
  name: 'Login',
  components: {
    Center,
    FormError
  },
  data () {
    return {
      userInfo: {
        loginId: '',
        loginPwd: ''
      },
      error: {
        loginId: '',
        loginPwd: ''
      }
    }
  },
  methods: {
    // 非空验证
    validateEmpty (field, msg) {
      if (this.userInfo[field]) {
        this.error[field] = ''
        return true
      } else {
        this.error[field] = msg
        return false
      }
    },
    // 确认密码验证
    validatePwdAgain () {
      var bool = this.validateEmpty('pwdAgain', '确认密码不能为空')
      if (bool) {
        if (this.userInfo.loginPwd !== this.userInfo.pwdAgain) {
          this.error.pwdAgain = '两次输入的密码不一致'
          return false
        }
        return true
      }
      return false
    },
    // 提交表单
    async handleSubmit () {
      if (this.$store.state.loginUser.isLoading) {
        // 正在登录中
        return
      }
      // 再次验证表单数据
      if (this.validateEmpty('loginId', '账号不能为空') &
        this.validateEmpty('loginPwd', '密码不能为空')
      ) {
        // 提交数据
        var res = await this.$store.dispatch('loginUser/login', this.userInfo)
        if (res) {
          // 登录成功, 跳转
          this.$router.push({ name: 'Home' })
        } else {
          this.error.loginId = '账号或密码不正确'
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  width: 400px;
}
.form-item {
  .input {
    display: flex;
  }
  label {
    width: 100px;
    display: inline-block;
    text-align: right;
    line-height: 41px;
  }
  .error {
    font-size: 14px;
    color: #a44242;
    padding-left: 100px;
    height: 30px;
    line-height: 30px;
    &.txt-center {
      text-align: center;
    }
  }
  input,
  button {
    flex-grow: 1;
  }
}
</style>
